//
//  QTopupMoneyVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/14.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QTopupMoneyVC.h"
#import "QPayStyleCell.h"
#import "QTopUPCell.h"
#import "QTopUpModel.h"
#import "LSXAlertInputView.h"
#import "QCurrentMoneyCell.h"
//#import "UILabel+BezierAnimation.h"
#define labWidth (kScreenWidth - 62)/3
#define fontSize 18


@interface QTopupMoneyVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tbView;
@property (nonatomic,strong)NSMutableArray *dataArr;
@end

@implementation QTopupMoneyVC{

    NSInteger _index;
    NSDictionary *_dataDic;
    NSString *_cType;//传参订单id
    NSString *_moneyStr;//传参金额
    NSString *_activityStr;//传参活动
    
    NSString *_activityMsg;//活动提示言
    UITextField *_textField1;
    NSMutableArray * _bridgeArr;//标签数据传输
    UILabel *_moneylab;//输入金额
    UILabel *_backlab;//反现金额
    UILabel *_accountlab;//到账金额
    BOOL _finished;
    BOOL isHaveDian;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"充值";
    _finished = NO;
    _index = 0;
    [self createTableView];
    [self requestData];
    [self setupForDismissKeyboard];//释放键盘

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiAction) name:kNotificationTopUpMoneySuccess object:nil];
   
    
}


//- (void)valueChanged{
//
//    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//    [_tbView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
//}

- (void)notifiAction{
    [self requestData];
}

#pragma mark --- createTableView
- (void)createTableView{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-50) style:UITableViewStyleGrouped];
    _tbView.dataSource = self;
    _tbView.delegate = self;
    _tbView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_tbView];
    
    [_tbView registerNib:[UINib nibWithNibName:@"QPayStyleCell" bundle:nil] forCellReuseIdentifier:@"QPayStyleCell"];
    [_tbView registerNib:[UINib nibWithNibName:@"QCurrentMoneyCell" bundle:nil] forCellReuseIdentifier:@"QCurrentMoneyCell"];
    
    UIButton *button = [QViewUtility createButtonWithFrame:CGRectMake(0, kScreenHeight-50, kScreenWidth, 50) font:16 title:@"支付" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [button blueStyle];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

//支付
- (void)buttonAction{
    //_moneyStr= @"0.01";
    
    NSLog(@"textField:%@",_textField1.text);
    if (_textField1.text == nil||[_textField1.text isEqualToString:@""]||[_textField1.text isEqualToString:@"0"]||[_textField1.text intValue]<0) {
         [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"充值金额不能为0" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
         return ;
    }
    
    _cType = @"";
    _moneyStr = _textField1.text;
    
    for (QTopUpModel *model in self.dataArr) {
        if ([model.payAmount intValue] == [_textField1.text intValue]) {
            _cType = model.rechargeId;
            _moneyStr = model.payAmount;
            _activityStr = model.activityType;
            
        }
    }
    
    if (_cType.length>0||_moneyStr.length>0) {
        [self payRequestData];
    }
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 1;
    }else if (section == 1){
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        static NSString *identify = @"QCurrentMoneyCell";
        
            QCurrentMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
            cell.backgroundColor = [UIColor whiteColor];
            cell.currentMoney.textColor = [QColorUtility defaultRedColor];
            if(_dataDic){
                cell.currentMoney.text = [NSString stringWithFormat:@"￥%@",_dataDic[@"balance"]];
                int num = [[_dataDic objectForKey:@"balance"]intValue];
                //[cell.detailTextLabel animationFromnum:0 toNum:num duration:3];
                [self setNumberTextOfLabel:cell.currentMoney WithAnimationForValueContent:num];
                [QUserInfo sharedInfo].loginModel.balance = _dataDic[@"balance"];
                [QDataUtility updateLoginModel:[QUserInfo sharedInfo].loginModel];
        }
       
        return cell;
    
    }else if (indexPath.section == 1){
        static NSString *identify = @"cells";
        QTopUPCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
        if(!cell){
            cell = [[QTopUPCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setCellWithData:_dataArr];
        __weak QTopupMoneyVC *wself = self;
        cell.block = ^(NSInteger index){
            __strong QTopupMoneyVC *sSelf = wself;
            if (index != _bridgeArr.count) {
                [sSelf->_textField1 resignFirstResponder];
                QTopUpModel * model = [sSelf->_bridgeArr objectAtIndex:index];
                sSelf->_textField1.text = [NSString stringWithFormat:@"%d",[model.payAmount intValue]];
                for (QTopUpModel *tmpModel in self.dataArr) {
                    if ([tmpModel.payAmount isEqualToString:model.payAmount]) {
                        _backlab.text = [NSString stringWithFormat:@"%d",[tmpModel.giftMoney intValue] ];
                        _accountlab.text = [NSString stringWithFormat:@"%d",[tmpModel.rechargeMoney intValue] ];
                    }
                }
                
            }else{
                
                [sSelf inputMoney];
            }
            
        };
        

//        cell.activeStr = _activityMsg;

        if(_finished == YES){
            _bridgeArr = [NSMutableArray array];
            for (QTopUpModel *model in _dataArr) {
                if ([model.activityType isEqualToString:@"1"]) {
                    [_bridgeArr addObject:model];
                }
            }
            cell.dataArr = _bridgeArr;
        }
        cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
        return cell;
    }else{
        QPayStyleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QPayStyleCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        cell.index= _index;
        cell.cIndexPath = indexPath;
        return cell;
    }
}

#pragma mark --- 弹出键盘
- (void)inputMoney{
    _textField1.text = @"";
    _backlab.text = @"0";
    _accountlab.text = @"0";
    [_textField1 becomeFirstResponder];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 1){
        QTopUPCell *cell = (QTopUPCell *)[self tableView:_tbView cellForRowAtIndexPath:indexPath];
        return cell.height+20;
    }else{
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _index = indexPath.row;
    [_tbView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 105;
    }
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        _cType = @"";
        _moneyStr = @"";
        _activityStr = @"";
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 105)];
        backView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        UIView *labView = [[UIView alloc] initWithFrame:CGRectMake(6, 15, kScreenWidth - 12, 70)];
        labView.backgroundColor = [UIColor whiteColor];
        labView.layer.cornerRadius = 4;
        labView.layer.masksToBounds = YES;
        [backView addSubview:labView];
        
        UILabel *adlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 96, kScreenWidth - 20, 10)];
        adlabel.centerX = backView.centerX;
        adlabel.textAlignment = 1;
        adlabel.font = [UIFont systemFontOfSize:13];
        adlabel.textColor = [QColorUtility defaultDeepGrayColor];

        NSMutableArray *strArr = [NSMutableArray array];
        
        for (QTopUpModel * model in _dataArr) {
            if ([model.activityType isEqualToString:@"2"]) {
                adlabel.text = [NSString stringWithFormat:@"充值%@元送%@元",model.sectionAmount,model.giftMoney];
                [strArr addObject:adlabel.text];
            }
        }
        adlabel.text = [strArr componentsJoinedByString:@","];

        [backView addSubview:adlabel];
    
        _textField1 = [[UITextField alloc]initWithFrame:CGRectMake(5, 17, labWidth, 20)];
        _textField1.delegate= self;
        _textField1.keyboardType = UIKeyboardTypeNumberPad;
        _textField1.borderStyle = UITextBorderStyleNone;
        _textField1.placeholder = @"请输入充值金额";
        _textField1.textAlignment = UITextAlignmentCenter;
        [_textField1 setValue:[UIFont boldSystemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
        _textField1.delegate = self;
        
        [_textField1 addTarget:self action:@selector(textFieldAction) forControlEvents:UIControlEventEditingChanged];
        [labView addSubview:_textField1];
        
        UILabel *small1 = [QViewUtility createLabelWithFrame:CGRectMake(0, _textField1.bottom + 6, 50, 10) font:14 textAlignment:1 textColor:[QColorUtility defaultDeepGrayColor] text:@"充值"];
        small1.centerX = _textField1.centerX;
        [labView addSubview:small1];
        
        
        UILabel *addlab = [QViewUtility createLabelWithFrame:CGRectMake(_textField1.right + 5, 17, 10, 20) font:fontSize textAlignment:1 textColor:[QColorUtility defaultBackColor] text:@"+"];
        [labView addSubview:addlab];
        
        _backlab = [QViewUtility createLabelWithFrame:CGRectMake(addlab.right + 5, 17, labWidth, 20) font:fontSize textAlignment:1 textColor:[QColorUtility defaultBackColor] text:@"0"];
        
        [labView addSubview:_backlab];
        UILabel *small2 = [QViewUtility createLabelWithFrame:CGRectMake(0, _backlab.bottom + 6, 50, 10) font:14 textAlignment:1 textColor:[QColorUtility defaultDeepGrayColor] text:@"返赠"];
        small2.centerX = _backlab.centerX;
        [labView addSubview:small2];

        
        UILabel *waitlab = [QViewUtility createLabelWithFrame:CGRectMake(_backlab.right + 5, 17, 10, 20) font:fontSize textAlignment:1 textColor:[QColorUtility defaultBackColor] text:@"="];
        [labView addSubview:waitlab];
        
        _accountlab = [QViewUtility createLabelWithFrame:CGRectMake(waitlab.right + 5, 17, labWidth, 20) font:fontSize textAlignment:1 textColor:[QColorUtility defaultBackColor] text:@"0"];
        UILabel *small3 = [QViewUtility createLabelWithFrame:CGRectMake(0, _accountlab.bottom + 6, 50, 10) font:14 textAlignment:1 textColor:[QColorUtility defaultDeepGrayColor] text:@"到账"];
        small3.centerX = _accountlab.centerX;
        [labView addSubview:small3];

        [labView addSubview:_accountlab];

        return backView;
    }
    return nil;
}

- (void)handleFinishBtn{
    
    [self resignFirstResponder];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [_textField1 resignFirstResponder];
}


#pragma mark--//获取充值的钱数
- (void)requestData{
    NSString *url = [QParamService urlWithAction:@"userRecharge"];
    NSDictionary *param = [QParamService topupMoney];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            _dataDic = basModel.items;
            _activityMsg = _dataDic[@"activityMsg"];
            self.dataArr = [QTopUpModel mj_objectArrayWithKeyValuesArray:[basModel.items objectForKey:@"rechargelist"]];
            _finished = YES;
            [_tbView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            if([basModel.errMsg isEqualToString:@"请重新登录"]){
                [QDataUtility deleteLoginModel];
            }
        }        
    }];
}

#pragma mark--//支付
- (void)payRequestData{
    NSString *zType;
    if(_index == 0){//微信
        zType = @"1";
    }else if (_index == 1){
        zType = @"2";
    }
    //_moneyStr = @"0.01";
    NSString *url = [QParamService urlWithAction:@"rechargeMoney"];

    NSDictionary *param = [QParamService topupFromWeChatWithType:zType denominationid:_cType money:_moneyStr activityType:_activityStr];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QUserInfo sharedInfo].payTypeStr = paytopup;
            if(_index == 0){
                 [QDataUtility gotoWeChatPay:basModel.items];//微信
            }else if(_index == 1){
                [QDataUtility gotoAliPayWithData:basModel.items];//支付宝
            }
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //敲删除键
    if ([string length]==0) {
        return YES;
    }
    //当输入框当前的字符个数大于18的时候，就不让更改了（不能等于18，因为如果等于18，在输入框字符个数等于18的情况下就不能进行粘贴替换内容了）
    if ([textField.text length]>7)
        return NO;
    //获得当前输入框内的字符串
    NSMutableString *fieldText=[NSMutableString stringWithString:textField.text];
    //完成输入动作，包括输入字符，粘贴替换字符
    [fieldText replaceCharactersInRange:range withString:string];
    NSString *finalText=[fieldText copy];
    //如果字符个数大于18就要进行截取前边18个字符
    if ([finalText length]>7) {
        textField.text=[finalText substringToIndex:7];
        return NO;
    }
    return YES;
}


#pragma mark --- 余额显示的动画----
- (void)setNumberTextOfLabel:(UILabel *)label WithAnimationForValueContent:(CGFloat)value
{
    CGFloat lastValue = [label.text floatValue];
    CGFloat delta = value - lastValue;
    if (delta == 0) {
        return;
    }
    
    if (delta > 0) {
        
        CGFloat ratio = value / 30.0;
        
        NSDictionary *userInfo = @{@"label" : label,
                                   @"value" : @(value),
                                   @"ratio" : @(ratio)
                                   };
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
}

- (void)setupLabel:(NSTimer *)timer
{
    NSDictionary *userInfo = timer.userInfo;
    UILabel *label = userInfo[@"label"];
    CGFloat value = [userInfo[@"value"] floatValue];
    CGFloat ratio = [userInfo[@"ratio"] floatValue];
    
    static int flag = 1;
    CGFloat lastValue = [label.text floatValue];
    CGFloat randomDelta = (arc4random_uniform(2) + 1) * ratio;
    CGFloat resValue = lastValue + randomDelta;
    
    if ((resValue >= value) || (flag == 50)) {
        label.text = [NSString stringWithFormat:@"¥%.2f", value];
        flag = 1;
        [timer invalidate];
        timer = nil;
        return;
    } else {
        label.text = [NSString stringWithFormat:@"%.2f", resValue];
    }
    flag++;
}

#pragma mark 点击TextField代理方法
-(void)textFieldAction{

    NSLog(@"textField:%@",_textField1.text);
    if ([_textField1.text isEqualToString:@""]) {
        [_textField1 resignFirstResponder];
    }
    _backlab.text = @"0";
    _accountlab.text = @"0";
    if (_textField1.text.length>0) {
        
         int num =  [_textField1.text intValue];
        NSString *stringFloat = [NSString stringWithFormat:@"%.2f",(double)num];
        _textField1.text = [NSString stringWithFormat:@"%d",num];
        _backlab.text = @"0";
        _accountlab.text = [NSString stringWithFormat:@"%d",num];
        
        for (QTopUpModel *tmpModel in self.dataArr) {
            
            if ([tmpModel.payAmount isEqualToString:stringFloat]) {
                _backlab.text = [NSString stringWithFormat:@"%d",[tmpModel.giftMoney intValue] ];
                _accountlab.text = [NSString stringWithFormat:@"%d",[tmpModel.rechargeMoney intValue]];
            }
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
        QTopUPCell *cell = [self.tbView cellForRowAtIndexPath:indexPath];
        [cell setSelectedBtnWithData:_textField1.text];
    
    }
  
   
}

ARRAY_INIT(dataArr);
@end
